안녕하세요 해당 제품 구매 후 사용중입니다.
처음에 초음파센서 배선 연결로 문제가 있어 연락드렸는데 지금은 배선 제대로 하고 작동하고 있습니다.
하지만 유튜브에서만 보던 영상과 동작이 조금 상이하여 문의드립니다.
경기장내에서 사용한게 아니라 그냥 거실 바닥에서 사용하였는데 불필요한 동작이 꽤나 있어 문의드립니다.
(장애물 감지 후 후진을 하고 다시 방향회전을 안거치고 다시 똑같은 위치로 가거나 제자리에서 계속 도는 행위 등..)
경기장도 구매하였는데 경기장에서 사용하면 좀 나을까요? 코드 한번만 점검 부탁드립니다...
유튜브 영상 내 경기장에서 시운전하는 코드 공유해주시면 감사하겠습니다.
작성코드
#include <SoftwareSerial.h>
#include <AFMotor.h>
AF_DCMotor motor_L(1);
AF_DCMotor motor_R(4);
int i;
//초음파센서 출력핀(trig)과 입력핀(echo), 변수, 함수 선언 //
int TrigPin = A0;
int EchoPin = A1;
long duration, distance;
void Obstacle_Check();
void Distance();
void Forward();
void Backward();
void Right();
void Left();
void Stop();
void setup() {
Serial.begin(9600); // PC와의 시리얼 통신속도
Serial.println("Eduino Smart Car Start!");
pinMode(EchoPin, INPUT); // EchoPin 입력
pinMode(TrigPin, OUTPUT); // TrigPin 출력
motor_L.setSpeed(160);
motor_L.run(RELEASE);
motor_R.setSpeed(180);
motor_R.run(RELEASE);
}
void loop() {
Forward();
delay(100);
Obstacle_Check();
}
//장애물 확인 및 회피 방향 결정//
void Obstacle_Check() {
int val = random(2);
Distance();
Serial.println(distance);
while (distance < 200) {
if (distance < 180) {
Backward();
delay(250);
Stop();
delay(50);
Distance();
}
else{
if (val ==0) {
Right();
delay(400);
}
else if (val ==1) {
Left();
delay(400);
}
Distance();
}
}
}
//거리 감지//
void Distance() {
digitalWrite(TrigPin, LOW);
delay(2);
digitalWrite(TrigPin, HIGH); // trigPin에서 초음파 발생(echoPin도 HIGH)
delayMicroseconds(10);
digitalWrite(TrigPin, LOW);
duration = pulseIn(EchoPin, HIGH); // echoPin이 HIGH를 유지한 시간을 저장 한다.
distance = ((float)(340 * duration)/1000) /2;
delay(5);
}
//방향 제어 함수//
void Forward() {
motor_L.run(FORWARD); motor_R.run(FORWARD);
for (i=0; i<200; i=i+20) {
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
for (i=0;i<200;i=i-20){
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
}
void Backward() {
motor_L.run(BACKWARD); motor_R.run(BACKWARD);
for (i=0; i<200; i=i+20) {
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
for (i=0;i<200;i=i-20){
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
}
void Right() {
motor_L.run(FORWARD); motor_R.run(BACKWARD);
for (i=0;i<180;i=i+20){
//j = i*1.3; if(j>=200) j = 200;
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
for (i=180; i<0; i=i-20){
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
}
void Left() {
motor_L.run(BACKWARD); motor_R.run(FORWARD);
for (i=0;i<180;i=i+20){
//j = i*1.3; if(j>=200) j = 200;
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
for (i=180; i<0; i=i-20){
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
}
void Stop() {
motor_L.run(RELEASE); motor_R.run(RELEASE);
for (i=200; i>=0; i=i-20) {
motor_L.setSpeed(i); motor_R.setSpeed(i);
delay(2);
}
}
거실 벽면이 가구 등으로 일정하지 않다보니 그런거 같아요!
장애물 확인시에 방향결정은 랜덤으로 설정되어 있어요.
경기장에서 하시면 보다 정확할 듯합니다!!